import { _decorator, Component, Node, sys } from 'cc'
import { Block } from './Game/Block'
import { LevelType } from './type'
import { GAME_STATUS_ENUM } from './Enum'
const { ccclass, property } = _decorator
const STORAGE_KEY = 'STORAGE_KEY'

@ccclass('DataManager')
export class DataManager {
  private static _inst: DataManager
  static get inst(): DataManager {
    if (this._inst == null) {
      this._inst = new DataManager()
    }
    return this._inst
  }
  private _level: number = 1 // 当前关卡
  get level(): number {
    return this._level
  }
  set level(value: number) {
    this._level = value
    this.save()
  }
  blocks: Block[] = [] // 存储所有方块
  records: Block[] = [] // 记录块
  currentLevel: LevelType = null // 当前关卡数据
  gameStatus: GAME_STATUS_ENUM = GAME_STATUS_ENUM.INIT
  clickable: boolean = false // 是否可点击，用于使用技能时所有块可点击
  // 初始化数据
  reset() {
    this.blocks = []
    this.records = []
    this.currentLevel = null
    this.gameStatus = GAME_STATUS_ENUM.INIT
    this.clickable = false
  }
  // 保存数据，下一关或重新开始时保存
  save() {
    sys.localStorage.setItem(
      STORAGE_KEY,
      JSON.stringify({
        currentLevel: this.currentLevel,
      }),
    )
  }
  // 读取数据
  reStore() {
    const _data = sys.localStorage.getItem(STORAGE_KEY)
    const data = JSON.parse(_data)
    if (data) {
      this.currentLevel = data.currentLevel || null
    }
  }
}
